﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebChatServer.Models;

namespace WebChatServer.Controllers
{
	[HttpHeader("Access-Control-Allow-Origin", "*")]
	[HttpHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")]
	public class PhotoController : ApiController
	{

		IMemberRepository _repository = new MemberRepository();
		ChatRepository _chatRepository = new ChatRepository();

		public Byte[] Share(string senderid, string fileName, string receiverid)
		{

			//Image img = file;
			string url = "ddd";
			Byte[] array;
			string path = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data/Photo/"));
			if (!Request.Content.IsMimeMultipartContent())
			{
				throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
			}
			var provider = new MultipartFormDataStreamProvider(path);

			var task = Request.Content.ReadAsMultipartAsync(provider);

			task.Wait();
			task.Dispose();

			foreach (var file in provider.BodyPartFileNames)
			{
				if (File.Exists(path + fileName))
				{
					File.Delete(path + fileName);
				}

				File.Copy(file.Value, path + fileName);
				_chatRepository.FileSend(senderid, fileName, receiverid);

				url = file.Value;
				array = _repository.GetImage(path + fileName);// + ".jpg");
				return array;
			}
			return new byte[0];
		}
	}
}